from flask import Blueprint, render_template, flash, redirect, url_for, session, request
from flask_login import login_required, login_user, logout_user, current_user

from apps.forms.login_form import LoginForm
from models.biz_enum import AccountStatus, SystemLogModule
from rules.system_log_rule import create_system_log
from rules.system_user_rule import search_system_user_by_username

admin = Blueprint('admin_login', __name__, url_prefix='/')


@admin.route('/')
@admin.route('/login', methods=['POST', 'GET'])
def login():
    if current_user.is_authenticated:
        next_page = request.args.get('next', default=url_for('admin_login.index'))
        # session["index_iframe_page"] = next_page
        return redirect(next_page)

    form = LoginForm()

    if request.method == 'GET':
        next_page = request.args.get('next', default=url_for('admin_login.index'))
        form.next_page.data = next_page

    if form.validate_on_submit():
        user_orm = search_system_user_by_username(form.username.data)
        if user_orm and user_orm.check_password(form.password.data) and user_orm.status == AccountStatus.NORMAL.value:
            flash('登录成功', 'success')
            login_user(user_orm)

            # 添加系统日志
            log_dict = dict(module=SystemLogModule.LOGIN, operation_detail=dict(), operator=user_orm.id)
            create_system_log(log_dict, True)

            if form.next_page.data:
                next_page = form.next_page.data
            else:
                next_page = url_for('admin_login.index')
            return redirect(next_page)
        else:
            flash('用户名或密码错误', 'error')

    return render_template('login.html', form=form)


@admin.route('/logout', methods=['POST', 'GET'])
@login_required
def logout():
    logout_user()
    session.pop('_flashes', None)
    flash('您已经退出登录', 'success')
    return redirect(url_for('admin_login.login'))


@admin.route('/index', methods=['POST', 'GET'])
@login_required
def index():
    return render_template('index.html')


@admin.route('/main', methods=['POST', 'GET'])
@login_required
def main():
    return render_template('main.html')
